package cn.juque.datapipeline.converter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>ResultSetConverter</li>
 * </ul>
 * @date 2023-04-06 11:18:33
 **/
@Component("resultSetConverter")
public class ResultSetConverter {

    public List<Map<String, Object>> resultSetToList(ResultSet resultSet) throws SQLException {
        List<Map<String, Object>> list = CollUtil.newArrayList();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        Map<String, Object> map;
        String columnName;
        while (resultSet.next()) {
            map = MapUtil.newHashMap();
            for (int i = 1; i <= columnCount; i++) {
                columnName = metaData.getColumnName(i);
                map.put(columnName, resultSet.getObject(columnName));
            }
            list.add(map);
        }
        return list;
    }
}
